<?php

class bannersOnRightWidgetComponents extends myComponents{

	public function executeRender(){
		$banners = $this->getBanners();

		$selected = array();
		foreach($banners as $id => $banner){
			$times = $banner['popularity'] > 0 ? $banner['popularity'] : 1;
			for($i = 1; $i <= $times; ++$i)
				$selected[] = $id;
		}


		shuffle($selected);

		$bannersToShow = 2;

		$this->result = new Doctrine_Collection('Banner');
		for($i = 0; $i < $bannersToShow && $i < count($selected); ++$i){
			$this->result->add($banners->get($selected[$i]));
			$selected = array_diff($selected, array($selected[$i]));
		}

	}



	protected function getBanners(){

		$result = new Doctrine_Collection('Banner');
		$result->setKeyColumn('id');


		$q = Doctrine::getTable('Banner')->createQuery('b')
			->select('b.*')
			->from('Banner b')
			->innerJoin('b.BannerGroup bg')
			->innerJoin('bg.StructureBannerGroups sbg')
			->innerJoin('sbg.Structure s WITH s.id = ?', $this->getRoute()->getObject()->getId())
			->where('bg.type = ?', 'commercial');

		$result = $result->merge($q->execute());

//		if($this->getRoute()->getCategoryObject()){
//			$q = Doctrine::getTable('Banner')->createQuery('b')
//				->select('b.*')
//				->from('Banner b')
//				->innerJoin('b.BannerGroup bg')
//				->innerJoin('bg.BannerGroups sbg')
//				->innerJoin('sbg.ProductGroup s WITH s.id = ?', $this->getRoute()->getCategoryObject()->getId())
//				->orderBy('b.pri asc')
//				->where('bg.type = ?', 'default')
//				->limit(4);
//
//
//			$result = $result->merge($q->execute());
//		}

		return $result;		
	}
}
